package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.commons.utils.Constants;
import com.tanhua.dubbo.api.ManagerApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManagerService {
    @DubboReference
    private ManagerApi managerApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage page1 = userInfoApi.findAll(page, pagesize);
        List<UserInfo> userInfos = page1.getRecords();
        userInfos.stream().forEach(userInfo -> {
            if (redisTemplate.hasKey(Constants.USER_FREEZE + userInfo.getId())) {
                userInfo.setUserStatus("2");
            }
        });
        return new PageResult(page, pagesize, page1.getTotal(), userInfos);
    }

    public UserInfo findUserById(Long userId) {
        UserInfo userInfo = userInfoApi.getById(userId);
        if (redisTemplate.hasKey(Constants.USER_FREEZE + userId)) {
            userInfo.setUserStatus("2");
        }
        return userInfo;
    }

    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {

        return videoApi.getByUserId(page, pagesize, uid);
    }


    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        PageResult pageResult = movementApi.findByUserId(uid, page, pagesize, state);
        List<Movement> movements = (List<Movement>) pageResult.getItems();
        if (movements == null) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(movements, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.getByIds(userIds, null);

        List<MovementsVo> movementsVoList = movements.stream().map((movement) -> {
            UserInfo userInfo = userInfoMap.get(movement.getUserId());
            if (userInfo != null) {
                return MovementsVo.init(userInfo, movement);
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return new PageResult(page, pagesize, pageResult.getCounts(), movementsVoList);
    }

    public Map<String, String> userFreeze(Map params) {
        //冻结范围，1登录，2发言，3发布动态
//        String freezingRange = params.get("freezingRange").toString();
//        //冻结原因
//        String reasonsForFreezing = params.get("reasonsForFreezing").toString();
//        //冻结备注
//        String frozenRemarks = params.get("frozenRemarks").toString();

        //冻结用户，存在redis中并设置时间
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;

        //冻结时间，1:3天，2:7天，3:永久
        String freezingTime = params.get("freezingTime").toString();
        int day = 0;
        if (freezingTime != null) {
            if (freezingTime.equals("1")) {
                day = 3;
            } else if (freezingTime.equals("2")) {
                day = 7;
            }
        }
        //将参数转成json作为redisValue
        String jsonString = JSON.toJSONString(params);

        if (day > 0) {
            redisTemplate.opsForValue().set(key, jsonString, day, TimeUnit.DAYS);
        } else {
            redisTemplate.opsForValue().set(key, jsonString);
        }
        //构造前端返回值
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("message", "冻结成功");
        return hashMap;
    }

    public Map<String, String> userUnFreeze(Map map) {
        String userId = map.get("userId").toString();
        //删除redis中的数据
        redisTemplate.delete(Constants.USER_FREEZE + userId);
        //构造前端返回值
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("message", "解冻成功");
        return hashMap;
    }

    public MovementsVo findByMovementId(String movementId) {
        Movement movement = movementApi.findByMovementId(movementId);
        if (movement == null) {
            return null;
        }
        Long userId = movement.getUserId();
        UserInfo userInfo = userInfoApi.getById(userId);
        return MovementsVo.init(userInfo, movement);
    }
}
